package com.gupaoedu.vip.netty.io.nio.buffer;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @program:gupaoedu-vip-netty-io
 * @description:直接缓冲区 零拷贝
 * 每次数据跨越用户态和内核态的边界，数据都需要拷贝，拷贝操作消耗CPU和内存带宽
 * @author:Gongchao
 * @date:2020-04-27
 **/
public class DirectBuffer {

    //在java里面存的是缓冲区的引用地址

    public static void main(String[] args) throws Exception {
        String inFile = "D://test.txt";
        FileInputStream fileInputStream = new FileInputStream(inFile);
        FileChannel fcin = fileInputStream.getChannel();

        //将读到的文件写入到一个新文件中
        String outFile = "D://testcope.txt";
        FileOutputStream fileOutputStream = new FileOutputStream(outFile);
        FileChannel fcout = fileOutputStream.getChannel();

        //使用allocateDirect，而不是allocate
        ByteBuffer buffer = ByteBuffer.allocateDirect(1024);

        while(true) {
            buffer.clear();

            int r = fcin.read(buffer);

            if(r == -1) {
                break;
            }

            buffer.flip();

            fcout.write(buffer);
        }
    }
}
